package com.yunfeng.supercall.activity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.OnEditorActionListener;

import com.lin.utils.DatabaseHelperForChattingMap;
import com.lin.utils.Session;
import com.lin.utils.Session.ResultReceiver;
import com.ly.quickdev.library.bean.Constants;
import com.ly.quickdev.library.manager.SelectPhotoManager;
import com.ly.quickdev.library.utils.ImageTools;
import com.ly.quickdev.library.utils.ImageTools.OnBitmapCreateListener;
import com.rockerhieu.emojicon.EmojiconGridFragment.OnEmojiconClickedListener;
import com.rockerhieu.emojicon.EmojiconsFragment;
import com.rockerhieu.emojicon.EmojiconsFragment.OnEmojiconBackspaceClickedListener;
import com.rockerhieu.emojicon.emoji.Emojicon;
import com.yunfeng.supercall.R;
import com.yunfeng.supercall.adapter.ChatMessageAdapter;
import com.yunfeng.supercall.app.AppContext;
import com.yunfeng.supercall.bean.ChatMessageBean;
import com.yunfeng.supercall.bean.ContactsBaseBean;
import com.yunfeng.supercall.bean.SuperFriendsBean;
import com.yunfeng.supercall.bean.UserBean;
import com.yunfeng.supercall.manager.ChatMessageManager;
import com.yunfeng.supercall.manager.ManagerFactory;
import com.yunfeng.supercall.manager.SuperFriendsManager;
import com.yunfeng.supercall.service.CallConnectionService;
import com.yzx.api.UCSMessage;
import com.yzx.api.UCSService;
import com.yzx.listenerInterface.RecordListener;
import com.yzx.tools.FileTools;
import com.yzx.tools.MapTools;

public class ChatActivity extends BaseActivity implements
OnEmojiconBackspaceClickedListener, OnEmojiconClickedListener,
SensorEventListener {

	private ListView mListView;// 显示聊天内容的List
	private View mVoiceIndicatorView;// 按下语音按键的时候，指示语音录制进度的view
	private List<ChatMessageBean> mChatMessages;// 聊天消息列表
	private ContactsBaseBean mContactsBase;// 传入的聊天对象
	private ChatMessageManager mChatMessageManager;// 聊天管理器
	private MessageReceiver mReceiver;// 监听来消息
	private ChatMessageAdapter mAdapter;// 列表数据适配器
	private View  mInputView, mMoreView, mEmojiView;
	private ImageView mButtonRecord;
	private String mVoicePath;// 录音路径
	private String mToUserPhoneCode;// 与之聊天的用户名
	private EditText mEditTextMsg;
	private Handler mHandler = new Handler();
	private int mScreenHeight;
	private TextView mTextViewCancel;
	private boolean mCancel;// 是否取消了录音
	private ImageView mImageViewRecording, mImageViewVoiceVolumeIndicator;// 标记正在录音
	private AnimationDrawable mAnimationDrawable;
	private long mLastTouchUp, mLastTouchDown;// 记录最后一次按下录音按钮的时间
	private ImageTools mImageTools;// 选取图片
	private List<ChatMessageBean> mTemp;
	private int mPageIndex = 1;
	private AudioManager mAudioManager;
	private Button mButtonSend;
	private Button mButtonRecordVoice;
	private EditText mEditTextTitle;
	//	private View mSwitchInputView;
	private View mFrameLayoutBack;
	private TextView mTextViewTitle;
	private UserBean mUserBean;
	// private SwipeRefreshLayout mSwipeRefreshLayout;//上拉加载更多，以后版本再实现吧
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_chat);
		mListView = findView(R.id.list);
		mUserBean = BaseActivity.getUser(getApplicationContext());
		// mSwipeRefreshLayout = findView(R.id.swipe);
		// mSwipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
		//
		// @Override
		// public void onRefresh() {
		// // TODO Auto-generated method stub
		// cutList();
		// }
		// });
		//		mSwitchInputView = findViewById(R.id.switchView);
		mButtonRecordVoice = findView(R.id.button_record_voice);
		mButtonSend = findView(R.id.btn_send);
		mButtonSend.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String text = mEditTextMsg.getText().toString();
				if (TextUtils.isEmpty(text)) {
					return;
				}
				sendMsg(text);
			}
		});
		mImageTools = new ImageTools(this);
		initFile();
		mScreenHeight = getWindowManager().getDefaultDisplay().getHeight();
		mButtonRecord = (ImageView) findViewById(R.id.btn_record);
		mMoreView = findViewById(R.id.more_area);
		//		mButtonArea = findViewById(R.id.button_area);
		mInputView = findViewById(R.id.input_view);
		mEmojiView = findViewById(R.id.emoji_area);
		findView(R.id.btn_voice).setOnTouchListener(
				new RecordButtonOnTouchListener());
		//		mButtonRecord = findView(R.id.btn_record);
		findView(R.id.button_record_voice).setOnTouchListener(
				new RecordButtonOnTouchListener());
		mFrameLayoutBack = findViewById(R.id.framelayout_back);
		mFrameLayoutBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		FrameLayout mFrameLayoutMore = (FrameLayout) findViewById(R.id.framelayout_more);
		mFrameLayoutMore.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//				Intent intent = new Intent(ChatActivity.this, FriendsDetailActivity.class);
				/*intent.putExtra(KEY_DATA, mContactsBase)
				.putExtra(
						KEY_IS_FRIEND,
						0);*/

				//				startActivity(intent);
				startActivityForResult(
						new Intent(ChatActivity.this, FriendsDetailActivity.class)
						.putExtra(KEY_DATA, mContactsBase)
						.putExtra(
								KEY_IS_FRIEND,
								mContactsBase.getType() == ContactsBaseBean.TYPE_ENTERPRISE),
								500);
			}
		});


		mChatMessageManager = ChatMessageManager.getInstance(this);
		mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
		boolean dial = getIntent().getBooleanExtra(KEY_CAN_NOT_DIAL, false);
		findView(R.id.dial).setVisibility(dial ? View.INVISIBLE : View.VISIBLE);
		mEditTextMsg = findView(R.id.et);


		mTextViewTitle = (TextView) findViewById(R.id.textview_title);
		mVoiceIndicatorView = findViewById(R.id.voice_indicator);
		mImageViewRecording = findView(R.id.ic_voice_indicator);
		mImageViewVoiceVolumeIndicator = findView(R.id.volume_indicator);
		mAnimationDrawable = (AnimationDrawable) mImageViewVoiceVolumeIndicator
				.getDrawable();
		mAnimationDrawable.stop();
		mTextViewCancel = findView(R.id.tv_cancel_record);

		mParentView = getActivity().findViewById(R.id.main_view);

		mParentView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
			@Override
			public void onGlobalLayout() {
				int heightDiff = mParentView.getRootView().getHeight() - mParentView.getHeight();
				if (heightDiff > 200) { // if more than 100 pixels, its probably a keyboard...
					//					mGridView.setVisibility(View.GONE);
					//					Log.i("WONIULU", "keyboard show");
					mEmojiView.setVisibility(View.GONE);


				} else {
				}
			}
		});


		mEditTextMsg.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {  
			@Override  
			public void onFocusChange(View v, boolean hasFocus) {  
				if(hasFocus) {
					// 此处为得到焦点时的处理内容
					mEmojiView.setVisibility(View.GONE);

				} else {
					// 此处为失去焦点时的处理内容
				}
			}
		});


		mEditTextMsg.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				if (s == null || s.length() == 0) {
					mButtonSend.setVisibility(View.GONE);
					//					mSwitchInputView.setVisibility(View.VISIBLE);
				} else {
					mButtonSend.setVisibility(View.VISIBLE);
					//					mSwitchInputView.setVisibility(View.GONE);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
		mEditTextMsg.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				// TODO Auto-generated method stub
				if (actionId == EditorInfo.IME_ACTION_SEND) {
					String text = mEditTextMsg.getText().toString();
					if (TextUtils.isEmpty(text)) {
						return false;
					}
					sendMsg(text);
					return true;
				}
				return false;

			}
		});
		mListView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				int action = event.getActionMasked();
				switch (action) {
				case MotionEvent.ACTION_MOVE:
					AppContext.closeIME(getActivity(), mEditTextMsg);
					break;
				}
				return false;
			}
		});
		handleIntent(getIntent());
		mReceiver = new MessageReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(ACTION_RECEIVE_MSG);
		registerReceiver(mReceiver, filter);
		/** 加入表情fragment */
		getSupportFragmentManager()
		.beginTransaction()
		.replace(
				R.id.emoji_area1,
				EmojiconsFragment
				.newInstance(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT))
				.commit();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		manager.cancelAll();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		super.onClick(v);
		switch (v.getId()) {
		case R.id.right_text:// 详情
			startActivityForResult(
					new Intent(this, FriendsDetailActivity.class)
					.putExtra(KEY_DATA, mContactsBase)
					.putExtra(
							KEY_IS_FRIEND,
							mContactsBase.getType() == ContactsBaseBean.TYPE_ENTERPRISE),
							500);
			break;
		}
	}

	/**
	 * 发送按钮
	 */
	public void send(View v) {
		String text = mEditTextMsg.getText().toString();
		if (TextUtils.isEmpty(text)) {
			return;
		}
		sendMsg(text);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
		setIntent(intent);
		handleIntent(intent);
	}

	/**
	 * 打开更多
	 */
	public void openMore(View v) {
		if (mMoreView.getVisibility() == View.GONE) {
			mMoreView.setVisibility(View.VISIBLE);
			AppContext.closeIME(getActivity(), mEditTextMsg);
			mEmojiView.setVisibility(View.GONE);
		} else {
			mEmojiView.setVisibility(View.GONE);

			mMoreView.setVisibility(View.GONE);
		}
	}

	/**
	 * 监听返回键，隐藏弹出的view
	 * 
	 */
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (mEmojiView.getVisibility() == View.VISIBLE) {
			mEmojiView.setVisibility(View.GONE);
			return;
		}
		if (mMoreView.getVisibility() == View.VISIBLE) {
			mMoreView.setVisibility(View.GONE);
			return;
		}
		SuperFriendsManager mFriendsManager = (SuperFriendsManager) ManagerFactory
				.createManager(SuperFriendsBean.class);
		SuperFriendsBean mFriends = mFriendsManager
				.findSuperFriendsByPhone(mContactsBase.getPhone());
		if (mFriends != null) {
			mFriends.setUnread(false);
			mFriends.setUnreadCount(0);
		}
		super.onBackPressed();
	}

	/**
	 * 显示表情view
	 * 
	 * @param v
	 */
	public void showEmoji(View v) {
		if (mEmojiView.getVisibility() == View.GONE) {
			mEmojiView.setVisibility(View.VISIBLE);
			mInputView.setVisibility(View.VISIBLE);
			mButtonRecordVoice.setVisibility(View.GONE);
			mMoreView.setVisibility(View.GONE);
			AppContext.closeIME(getActivity(), mEditTextMsg);
			mMoreView.setVisibility(View.GONE);

		} else {
			mMoreView.setVisibility(View.GONE);

			AppContext.closeIME(getActivity(), mEditTextMsg);
			mEmojiView.setVisibility(View.GONE);
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		mEmojiView.setVisibility(View.GONE);
		mMoreView.setVisibility(View.GONE);
	}

	public void call(View v) {
		startActivity(new Intent(this, OutCallActivity.class).putExtra(
				KEY_DATA, mContactsBase));
	}

	@SuppressWarnings("unused")
	private void cutList() {
		int size = mChatMessages.size();
		List<ChatMessageBean> temp = new ArrayList<ChatMessageBean>();
		if (mPageIndex >= (size / 10)) {
			int count = mPageIndex * 10;
			count = 10 - (size - count);
			for (int i = count; i < size; i++) {
				temp.add(mChatMessages.get(size - i));
			}
		} else {
			for (int i = size - (mPageIndex * 10); i < size
					- ((mPageIndex - 1) * 10); i++) {
				temp.add(mChatMessages.get(i));
			}
		}
		mTemp.addAll(0, temp);
		// mSwipeRefreshLayout.setRefreshing(false);
		mPageIndex++;
		if (mAdapter != null) {
			mAdapter.notifyDataSetChanged();
			mListView.setSelection(10);
		}
	}

	/**
	 * 处理intent，用户可能会从通知栏点击聊天通知，需再次处理新的intent
	 * 
	 * @param intent
	 */
	private void handleIntent(Intent intent) {
		mContactsBase = getIntent().getParcelableExtra(KEY_DATA);
		if (mContactsBase instanceof SuperFriendsBean) {
			mToUserPhoneCode = ((SuperFriendsBean) mContactsBase).getVo_id();
		}

		mTextViewTitle.setText(mContactsBase.getNick_name());
		refreshList();
		mChatMessages = findChatMessages(mContactsBase);
		//		mChatMessages = mChatMessageManager.findChatMessages(mContactsBase);
		// if (mChatMessages.size() < 10) {
		// mTemp = mChatMessages;
		// } else {
		// mTemp = new ArrayList<ChatMessage>();
		// cutList();
		// }
		//		mListView.setAdapter(mAdapter = new ChatMessageAdapter(getActivity(),
		//				mChatMessages, mContactsBase));
		//		if (mAdapter.getCount() > 1) {
		//			mListView.setSelection(mAdapter.getCount());
		//		}
		setTitleBar(mContactsBase.getNick_name());
	}

	/**
	 * 选择要发送的图片
	 * 
	 * @param v
	 */
	public void selectPhoto(View v) {
		// mImageTools.openGallery();
		// mImageTools.showGetImageDialog("选择图片");
		Builder mBuilder = new Builder(getActivity());
		mBuilder.setCancelable(true);
		mBuilder.setTitle(R.string.choose_photo);
		mBuilder.setItems(R.array.select_choose_photo_mode,
				new Dialog.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				switch (which) {
				case 0:
					mImageTools.openCamara();
					break;

				case 1:
					SelectPhotoManager.getInstance().setLimite(9);
					List<String> list = SelectPhotoManager
							.getInstance().getPhotos();
					list.clear();
					startActivityForResult(
							new Intent(getActivity(),
									SuperChoosePhotoActivity.class)
							.setAction(Constants.ACTION_CHOOSE_PHOTO_MULTI),
							400);
					break;
				}
			}
		});
		mBuilder.show();
	}

	/**
	 * 发送位置
	 * 
	 * @param v
	 */
	public void location(View v) {
		sendLocation();
	}

	/**
	 * 切换输入的view
	 * 
	 * @param v
	 */
	public void switchInputView(View v) {
		if (mInputView.getVisibility() == View.GONE) {
			mEmojiView.setVisibility(View.GONE);

			mInputView.setVisibility(View.VISIBLE);
			mEditTextMsg.requestFocus();
			AppContext.openIME(this, mEditTextMsg);
			mButtonRecordVoice.setVisibility(View.GONE);
			mMoreView.setVisibility(View.GONE);
			mButtonRecord.setImageDrawable(getResources().getDrawable(R.drawable.ic_bg_send_voice));
			mButtonSend.setVisibility(View.VISIBLE);
		} else {
			mEmojiView.setVisibility(View.GONE);

			mButtonSend.setVisibility(View.GONE);
			mButtonRecord.setImageDrawable(getResources().getDrawable(R.drawable.ic_keyboard));
			mMoreView.setVisibility(View.GONE);
			mButtonRecordVoice.requestFocus();
			AppContext.closeIME(getActivity(), mEditTextMsg);
			mInputView.setVisibility(View.GONE);
			mButtonRecordVoice.setVisibility(View.VISIBLE);
		}
	}

	private void initFile() {
		File file = new File(Environment.getExternalStorageDirectory()
				.getAbsolutePath() + "/yunzhixun/");

		// File nomedia = new File(file.getAbsolutePath() + "/.nomedia");
		File nomedia = new File(file.getAbsolutePath(), ".nomedia");
		if (!nomedia.exists()) {
			try {
				nomedia.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	/**
	 * 发送位置
	 */
	private void sendLocation() {
		if (!UCSService.isConnected()) {
			showToast(R.string.unconnect_to_chat_server);
			return;
		}
		String location = MapTools.combinationLocationJson(AppContext.addr,
				AppContext.lng + "", AppContext.lat + "");
		mChatMessageManager.putMessages(mContactsBase,
				generateChatMessage(ChatMessageBean.TYPE_LOCATION, location));
		refreshList();
		refreshMsgList();

		UCSMessage.sendUcsMessage(mToUserPhoneCode.toString(), location, null,
				LOCATION);

		Session mSession = Session.getSession();
		mSession.init(getApplicationContext(), true);
		String phone = mContactsBase.getPhone();
		/*if(TextUtils.isEmpty(otherPhone)) {
			phone = otherPhone2;
		}*/
		mSession.SendPushMsg(getApplicationContext(), mUserBean.getNick_name() +"向您分享了地理位置" , 1, phone,mUserBean.getNick_name() +"向您分享了地理位置", new ResultReceiver<Integer>() {

			@Override
			public void onResult(boolean last, Integer args) {
				// TODO Auto-generated method stub

			}

		});
	}

	/**
	 * 发送语音
	 * 
	 * @param path
	 */
	Handler handlerInternet = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			Toast.makeText(getApplicationContext(), getResources().getString(R.string.unconnect_to_chat_server), Toast.LENGTH_SHORT).show();
		}

	};
	private void sendVoiceMsg(final String path) {
		if (!UCSService.isConnected()) {
			//			showToast(R.string.unconnect_to_chat_server);


			handlerInternet.sendEmptyMessage(0);
			return;
		}
		mChatMessageManager.putMessages(mContactsBase,
				generateChatMessage(ChatMessageBean.TYPE_VOICE, path));
		refreshList();
		refreshMsgList();
		new Thread() {
			public void run() {
				UCSMessage.sendUcsMessage(mToUserPhoneCode, null, path,
						UCSMessage.VOICE);
			};
		}.start();

		Session mSession = Session.getSession();
		mSession.init(getApplicationContext(), true);
		String phone = mContactsBase.getPhone();
		/*if(TextUtils.isEmpty(otherPhone)) {
			phone = otherPhone2;
		}*/
		mSession.SendPushMsg(getApplicationContext(), mUserBean.getNick_name() +"向您发送了语音信息" , 1, phone,mUserBean.getNick_name() +"向您发送了语音信息", new ResultReceiver<Integer>() {

			@Override
			public void onResult(boolean last, Integer args) {
				// TODO Auto-generated method stub

			}

		});
	}

	private void sendMsg(final String text) {
		if (!UCSService.isConnected()) {
			showToast(R.string.unconnect_to_chat_server);
			return;
		}
		mChatMessageManager.putMessages(mContactsBase,
				generateChatMessage(ChatMessageBean.TYPE_TEXT, text));
		mEditTextMsg.setText("");
		refreshList();
		refreshMsgList();
		new Thread() {
			public void run() {
				UCSMessage.sendUcsMessage(mToUserPhoneCode, text, null,
						UCSMessage.TEXT);
			};
		}.start();
		Session mSession = Session.getSession();
		mSession.init(getApplicationContext(), true);
		String phone = mContactsBase.getPhone();
		/*if(TextUtils.isEmpty(otherPhone)) {
			phone = otherPhone2;
		}*/
		mSession.SendPushMsg(getApplicationContext(), mUserBean.getNick_name() +"给您留言" , 1, phone,text, new ResultReceiver<Integer>() {

			@Override
			public void onResult(boolean last, Integer args) {
				// TODO Auto-generated method stub

			}

		});
	}

	/**
	 * 发送图片
	 * 
	 * @param path
	 */
	private void sendImgMsg(final String path) {
		if (!UCSService.isConnected()) {
			showToast(R.string.unconnect_to_chat_server);
			return;
		}
		mChatMessageManager.putMessages(mContactsBase,
				generateChatMessage(ChatMessageBean.TYPE_PIC, path));
		refreshList();
		refreshMsgList();
		new Thread() {
			public void run() {
				UCSMessage.sendUcsMessage(mToUserPhoneCode, null, path,
						UCSMessage.PIC);
			};
		}.start();

		Session mSession = Session.getSession();
		mSession.init(getApplicationContext(), true);
		String phone = mContactsBase.getPhone();
		/*if(TextUtils.isEmpty(otherPhone)) {
			phone = otherPhone2;
		}*/
		mSession.SendPushMsg(getApplicationContext(), mUserBean.getNick_name() +"给您发送了一张图片" , 1, phone,mUserBean.getNick_name() +"给您发送了一张图片", new ResultReceiver<Integer>() {

			@Override
			public void onResult(boolean last, Integer args) {
				// TODO Auto-generated method stub

			}

		});
	}

	/**
	 * 根据消息类型和内容构造ChatMessage对象
	 * 
	 * @param type
	 * @param content
	 * @return
	 */
	private ChatMessageBean generateChatMessage(int type, String content) {
		ChatMessageBean chatMessage = new ChatMessageBean();
		chatMessage.setChatType(type);
		chatMessage.setContent(content);
		chatMessage.setSendFromMySelf(true);
		chatMessage.setMsgFrom(getUser(getActivity()).getVo_id());
		chatMessage.setMsgTo(mToUserPhoneCode);
		chatMessage.setReceiveTime(System.currentTimeMillis());
		if (type == ChatMessageBean.TYPE_VOICE) {
			chatMessage
			.setVoiceLenth(UCSMessage.getVoiceDuration(content) / 1000);
		}
		if (!UCSService.isConnected()) {
			startService(new Intent(this, CallConnectionService.class));
		}
		return chatMessage;
	}

	/**
	 * 刷新聊天列表
	 */
	private void refreshMsgList() {
		mHandler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				mAdapter.notifyDataSetChanged();
				int count = mAdapter.getCount();
				if (count > 1) {
					mListView.smoothScrollToPosition(mAdapter.getCount() - 1);
				}
			}
		});

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (UCSMessage.isPlaying()) {
			UCSMessage.stopPlayerVoice();
		}
		unregisterReceiver(mReceiver);
		mAdapter.releaseSensors();
		mAudioManager.setMode(AudioManager.MODE_NORMAL);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case ImageTools.GALLERY:
				Uri selectedImage = data.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA };

				Cursor cursor = this.getContentResolver().query(selectedImage,
						filePathColumn, null, null, null);
				cursor.moveToFirst();

				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				String filePath = cursor.getString(columnIndex);
				sendImgMsg(filePath);
				break;
			case ImageTools.CAMARA:
				mImageTools.getBitmapFromCamara(new OnBitmapCreateListener() {

					@Override
					public void onBitmapCreate(Bitmap bitmap, String path) {
						// TODO Auto-generated method stub
						sendImgMsg(path);
					}
				});
				break;
			case 500:
				if (data.getBooleanExtra(KEY_DATA, false)) {
					finish();
				}
				break;
			case 400:
				List<String> paths = data.getStringArrayListExtra("data");
				for (String s : paths) {
					sendImgMsg(s);
				}
				break;
			}
		}
	}

	/**
	 * 监听来消息
	 * 
	 * @author 洋
	 * 
	 */
	public class MessageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			try {
				String action = intent.getAction();
				if (ACTION_RECEIVE_MSG.equals(action)) {

					refreshList();

					ChatMessageBean chatMessage = intent.getParcelableExtra(KEY_DATA);
					if(chatMessage !=null) {
						if(chatMessage.getMsgFrom() != null) {
							if (chatMessage.getMsgFrom().equalsIgnoreCase(mToUserPhoneCode)) {
								refreshMsgList();
							}
						}
					} else {
						refreshMsgList();
					}
				}
			} catch(Exception e) {
				e.printStackTrace();
			}
		}


	}

	private void refreshList() {
		try {

			mHandlerRefreshList.sendEmptyMessage(0);
		} catch(Exception e) {

		}
		/*	Handler mHandler = new Handler();
		mHandler.post(new Runnable() {
			@Override
			public void run() {

			}
		});*/
	}
	private Handler mHandler2 = new Handler(){ 
		@Override
		public void handleMessage(Message msg)
		{
			mAdapter.setmList(mChatMessages);
			mAdapter.notifyDataSetChanged();
			int count = mAdapter.getCount();
			if (count > 1) {
				mListView.smoothScrollToPosition(mAdapter.getCount() - 1);
			}
		}
	};

	private Handler mHandlerRefreshList = new Handler(){ 
		@Override
		public void handleMessage(Message msg)
		{
			mChatMessages = findChatMessages(mContactsBase);
			if(mAdapter != null) {
				mHandler2.sendEmptyMessage(0);

			} else {
				mListView.setAdapter(mAdapter= new ChatMessageAdapter(getActivity(),
						mChatMessages, mContactsBase));
			}
			if (mAdapter.getCount() > 1) {
				mListView.setSelection(mAdapter.getCount());
			}

		}
	};
	private View mParentView;

	/**
	 * 录音按钮的监听器
	 * 
	 * @author 洋
	 * 
	 */
	class RecordButtonOnTouchListener implements OnTouchListener {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				if (System.currentTimeMillis() - mLastTouchDown < 1000) {
					mCancel = true;
					return true;
				}
				mLastTouchDown = System.currentTimeMillis();
				v.setPressed(true);
				mCancel = false;
				mVoiceIndicatorView.setVisibility(View.VISIBLE);
				mVoicePath = FileTools.createAudioFileName(mToUserPhoneCode);
				mAnimationDrawable.start();
				try {
					UCSMessage.startVoiceRecord(mVoicePath,
							new RecordListener() {

						@Override
						public void onFinishedRecordingVoice(int arg0) {
							// TODO Auto-generated method stub
							if (!mCancel
									&& mLastTouchUp - mLastTouchDown > 1000) {
								sendVoiceMsg(mVoicePath);
							}
						}

						@Override
						public void onFinishedPlayingVoice() {
							// TODO Auto-generated method stub
						}
					});
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				break;
			case MotionEvent.ACTION_CANCEL:
			case MotionEvent.ACTION_UP:
				v.setPressed(false);

				mVoiceIndicatorView.setVisibility(View.GONE);
				mAnimationDrawable.stop();
				mLastTouchUp = System.currentTimeMillis();
				try {
					UCSMessage.stopVoiceRecord();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				break;
			case MotionEvent.ACTION_MOVE:
				float y = Math.abs(event.getY());
				if (y > mScreenHeight / 3 && y < mScreenHeight / 3 * 2) {
					mImageViewRecording.setImageResource(R.drawable.ic_cancel);
					mTextViewCancel
					.setText(R.string.release_to_cancel_recording);
					mTextViewCancel
					.setBackgroundResource(R.drawable.ic_cancel_tv);
					mCancel = true;

				} else {
					mCancel = false;
					mImageViewRecording
					.setImageResource(R.drawable.ic_recording);
					mTextViewCancel
					.setBackgroundResource(android.R.color.transparent);

					mTextViewCancel
					.setText(R.string.slide_up_to_cancel_recording);
				}
				break;
			}
			return true;
		}

	}

	@Override
	public void onEmojiconClicked(Emojicon emojicon) {
		// TODO Auto-generated method stub
		EmojiconsFragment.input(mEditTextMsg, emojicon);
	}

	@Override
	public void onEmojiconBackspaceClicked(View v) {
		// TODO Auto-generated method stub
		EmojiconsFragment.backspace(mEditTextMsg);
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		// TODO Auto-generated method stub
		float[] its = event.values;
		// Log.d(TAG,"its array:"+its+"sensor type :"+event.sensor.getType()+" proximity type:"+Sensor.TYPE_PROXIMITY);
		if (its != null && event.sensor.getType() == Sensor.TYPE_PROXIMITY) {

			System.out.println("its[0]:" + its[0]);

			// 经过测试，当手贴近距离感应器的时候its[0]返回值为0.0，当手离开时返回1.0
			if (its[0] == 0.0) {// 贴近手机
				mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
				// System.out.println("hands up");
				// if (mWakeLockScreen.isHeld()) {
				// return;
				// } else {
				//
				// mWakeLockScreen.acquire();// 申请设备电源锁
				// }
			} else {// 远离手机
				mAudioManager.setMode(AudioManager.MODE_NORMAL);
				// System.out.println("hands moved");
				// if (mWakeLockScreen.isHeld()) {
				// return;
				// } else {
				// mWakeLockScreen.setReferenceCounted(false);
				// mWakeLockScreen.release(); // 释放设备电源锁
				// }
			}
		}
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub

	}

	public ArrayList<ChatMessageBean> findChatMessages(ContactsBaseBean base) {
		ArrayList<ChatMessageBean> messages = new ArrayList<ChatMessageBean>();

		/*DatabaseHelperForChattingMap dbHelper5 = new DatabaseHelperForChattingMap(getActivity(), "db", 2);  
		SQLiteDatabase db5 = dbHelper5.getReadableDatabase();  
		//创建游标对象  
		Cursor cursor = db5.query("UCSMessage", new String[]{"id","idr","chatType","content", "msgFrom","msgId", "msgTo", "receiveTime", "voiceLength", "isread", "UnreadCount"}, null, null, null, null, null, null);  
		//利用游标遍历所有数据对象  
		while(cursor.moveToNext()){  
			int id = cursor.getInt(cursor.getColumnIndex("id"));
			String idr =  cursor.getString(cursor.getColumnIndex("idr"));
			String chatType =  cursor.getString(cursor.getColumnIndex("chatType"));
			String content =  cursor.getString(cursor.getColumnIndex("content"));
			String msgFrom =  cursor.getString(cursor.getColumnIndex("msgFrom"));
			String msgId =  cursor.getString(cursor.getColumnIndex("msgId"));
			String msgTo =  cursor.getString(cursor.getColumnIndex("msgTo"));
			String receiveTime =  cursor.getString(cursor.getColumnIndex("receiveTime"));
			String voiceLength =  cursor.getString(cursor.getColumnIndex("voiceLength"));
			String isread =  cursor.getString(cursor.getColumnIndex("isread"));
			String UnreadCount =  cursor.getString(cursor.getColumnIndex("UnreadCount"));
			//日志打印输出  
			Log.i("TAG","query-->"+content);  
		}  
		db5.close();
		dbHelper5.close();*/


		DatabaseHelperForChattingMap dbHelper7 = new DatabaseHelperForChattingMap(getActivity(), "db", 2);  
		SQLiteDatabase db7 = dbHelper7.getReadableDatabase();  
		//创建游标对象  
		String name;
		if (base instanceof SuperFriendsBean) {
			name = ((SuperFriendsBean) base).getVo_id();
		} else {
			name = base.getPhone();
		}
		String mSelfCode = BaseActivity.getUser(getActivity()).getVo_id();;
		Cursor cursor2 = db7.query("UCSMessage", new String[]{"id","idr","chatType","content", "msgFrom","msgId", "msgTo", "receiveTime", "voiceLength", "isread", "UnreadCount"}, "(msgFrom='" + name + "' and msgTo= '" + mSelfCode
				+ "') or (msgFrom='" + mSelfCode
				+ "' and msgTo = '" + name + "')", null, null, null, null, null);  
		//利用游标遍历所有数据对象  
		while(cursor2.moveToNext()){ 
			ChatMessageBean mChatMessageBean = new ChatMessageBean();

			int id = cursor2.getInt(cursor2.getColumnIndex("id"));
			String idr =  cursor2.getString(cursor2.getColumnIndex("idr"));
			String chatType =  cursor2.getString(cursor2.getColumnIndex("chatType"));
			String content =  cursor2.getString(cursor2.getColumnIndex("content"));
			String msgFrom =  cursor2.getString(cursor2.getColumnIndex("msgFrom"));
			String msgId =  cursor2.getString(cursor2.getColumnIndex("msgId"));
			String msgTo =  cursor2.getString(cursor2.getColumnIndex("msgTo"));
			String receiveTime =  cursor2.getString(cursor2.getColumnIndex("receiveTime"));
			String voiceLength =  cursor2.getString(cursor2.getColumnIndex("voiceLength"));
			String isread =  cursor2.getString(cursor2.getColumnIndex("isread"));
			String UnreadCount =  cursor2.getString(cursor2.getColumnIndex("UnreadCount"));

			Log.i("TAG", chatType + " content:" + "");
			if(msgFrom.equals(mSelfCode)){
				mChatMessageBean.setSendFromMySelf(true);
			} else {
				mChatMessageBean.setSendFromMySelf(false);	
			}
			mChatMessageBean.setId(id);
			mChatMessageBean.setChatType(Integer.parseInt(chatType));
			mChatMessageBean.setContent(content);
			mChatMessageBean.setMsgFrom(msgFrom);
			mChatMessageBean.setMsgId(msgId);
			mChatMessageBean.setMsgTo(msgTo);
			mChatMessageBean.setReceiveTime(Long.parseLong(receiveTime));;
			mChatMessageBean.setVoiceLenth(Integer.parseInt(voiceLength));
			mChatMessageBean.setHasRead(Integer.parseInt(isread) == 0 ? true : false);
			messages.add(mChatMessageBean);
			//日志打印输出  
		}


		return messages;
	}

}
